package com.zhiwei.common.util;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * functipn: 反射类工具类
 * author: zhiwei_yang
 * time: 2020/5/4-22:38
 */
@Slf4j
public final class ReflectionUtils {

    /**
     * 设置属性值
     *
     * @param target
     */
    public static boolean setPropertyValue(Object target, String propertyName, Object value) {
        try {
            Field field = target.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            field.set(target, value);
            return true;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.error("对象[{}]不存在执行字段:{}", target.getClass().getName(), propertyName, e);
            return false;
        }
    }

    /**
     * 获取属性值
     *
     * @param target
     */
    public static <T> T getPropertyValue(Object target, String propertyName) {
        try {
            Field field = target.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);
            return (T) field.get(target);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}
